$(document).ready(function () {
    // Load projects on page load
    loadProjects();

    // Add project form submission
    $('#add-project-form').submit(function (e) {
        e.preventDefault();
        addProject();
    });
});

function loadProjects() {
    $.ajax({
        url: '/projects/list',
        method: 'GET',
        success: function (data) {
            $('#projects-table tbody').empty();
            data.forEach(function (project) {
                const row = `
                    <tr data-id="${project.id}">
                        <td>${project.id}</td>
                        <td>${project.name}</td>
                        <td>${project.description}</td>
                        <td>${new Date(project.created_at).toLocaleString()}</td>
                        <td>
                            <button class="btn btn-danger btn-sm view-btn">查看</button>
                            <button class="btn btn-danger btn-sm delete-btn">Delete</button>
                        </td>
                    </tr>
                `;
                $('#projects-table tbody').append(row);
            });
            attachDeleteHandlers();
            attachViewHandlers();
        }
    });
}

function addProject() {
    const projectData = {
        name: $('#name').val(),
        description: $('#description').val()
    };

    $.ajax({
        url: '/projects/list',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(projectData),
        success: function () {
            loadProjects();
            $('#add-project-form')[0].reset();
        }
    });
}

function attachDeleteHandlers() {
    $('.delete-btn').click(function () {
        const projectId = $(this).closest('tr').data('id');
        deleteProject(projectId);
    });
}

function attachViewHandlers(){
    $('.view-btn').click(function () {
        const projectId = $(this).closest('tr').data('id');
        //页面跳转
        window.location.href = `/flowchart/${projectId}`;
    });
}

function deleteProject(projectId) {
    if (confirm('Are you sure you want to delete this project?')) {
        $.ajax({
            url: `/api/projects/${projectId}`,
            method: 'DELETE',
            success: function () {
                loadProjects();
            }
        });
    }
}
